package utils;

import book.PairOfUserIdAndBookId;
import com.bit.utils.FileUtils;

import java.io.IOException;
import java.util.Arrays;

public class AnalyzingBorrowedBook {

    public void storeObject(PairOfUserIdAndBookId[] pairOfUserIdAndBookIds,String filename) throws IOException {
        int bookBorrowLen = 0;
        for (int i = 0; i < pairOfUserIdAndBookIds.length; i++) {
            if (pairOfUserIdAndBookIds[i] != null) {
                bookBorrowLen++;
            }
        }

        StringBuilder jsonArray = new StringBuilder();

        for (int i = 0; i < bookBorrowLen; i++) {
            if (pairOfUserIdAndBookIds[i] != null) {
                jsonArray.append(pairOfUserIdAndBookIds[i].toJson());
                if (i != bookBorrowLen - 1) {
                    jsonArray.append("\n");
                }
            }
        }

        FileUtils.writeFile(jsonArray.toString(),filename);
    }

    public PairOfUserIdAndBookId[] loadObject(String filename) throws IOException {
        //从文件中读取数据
        String content = FileUtils.readFile(filename);
        if (content == null || content.isEmpty()) {
            System.out.println("已借阅书籍列表无数据，表示没有用户借阅过书籍");
            return null;
        }

        //将字符串进行分割成 1,1001  2,1002
        String[] jsonStrings = content.split("\n");

        //定义PairOfUserIdAndBookId数组 进行分割后的整型接收
        PairOfUserIdAndBookId[] pairOfUserIdAndBookIds = new PairOfUserIdAndBookId[jsonStrings.length];

        for (int i = 0; i < jsonStrings.length; i++) {

            PairOfUserIdAndBookId pairOfUserIdAndBookId = new PairOfUserIdAndBookId();

            String[] UserIdAndBookId = jsonStrings[i].split(",");

            pairOfUserIdAndBookId.setUserId(Integer.parseInt(UserIdAndBookId[0]));
            pairOfUserIdAndBookId.setISBN(Integer.parseInt(UserIdAndBookId[1]));

            pairOfUserIdAndBookIds[i] = pairOfUserIdAndBookId;

        }

        return pairOfUserIdAndBookIds;

    }
}
